from typing import Dict, List, Optional
import json
import os
from datetime import datetime

class PromptManager:
    """Prompt模板管理器，负责模板的加载、存储和管理"""
    def __init__(self):
        self.templates_dir = 'templates'
        self.templates_file = os.path.join(self.templates_dir, 'templates.json')
        self.templates = self.load_templates()
        
    def load_templates(self) -> Dict:
        """加载所有模板"""
        try:
            if not os.path.exists(self.templates_dir):
                os.makedirs(self.templates_dir)
                
            if os.path.exists(self.templates_file):
                with open(self.templates_file, 'r', encoding='utf-8') as f:
                    return json.load(f)
            return self._create_default_templates()
        except Exception as e:
            print(f'加载模板失败: {e}')
            return self._create_default_templates()
    
    def _create_default_templates(self) -> Dict:
        """创建默认模板"""
        default_templates = {
            'translation': {
                'name': '翻译',
                'description': '将文本翻译成指定语言',
                'content': '请将以下文本翻译成{target_language}：\n{source_text}',
                'variables': ['source_text', 'target_language'],
                'source_text': '',
                'target_language': '',
                'category': '语言',
                'created_at': datetime.now().isoformat()
            },
            'explanation': {
                'name': '解释说明',
                'description': '详细解释文本内容',
                'content': '请详细解释以下内容：\n{text}',
                'variables': ['text'],
                'text': '',
                'category': '理解',
                'created_at': datetime.now().isoformat()
            },
            'summary': {
                'name': '总结',
                'description': '简要总结文本要点',
                'content': '请用简洁的语言总结以下内容的要点：\n{text}',
                'variables': ['text'],
                'text': '',
                'category': '理解',
                'created_at': datetime.now().isoformat()
            }
        }
        self.save_templates(default_templates)
        return default_templates
    
    def save_templates(self, templates: Dict = None) -> bool:
        """保存模板到文件"""
        try:
            if templates is None:
                templates = self.templates
            with open(self.templates_file, 'w', encoding='utf-8') as f:
                json.dump(templates, f, indent=4, ensure_ascii=False)
            return True
        except Exception as e:
            print(f'保存模板失败: {e}')
            return False
    
    def load_template(self, template_name: str) -> Dict:
        """加载指定模板"""
        if template_name not in self.templates:
            raise KeyError(f'模板 {template_name} 不存在')
        return self.templates[template_name]
    
    def save_template(self, template: Dict) -> bool:
        """保存单个模板"""
        if not template.get('name'):
            return False
        template_name = template['name']
        self.templates[template_name] = template
        return self.save_templates()
    
    def update_template(self, template_name: str, updates: Dict) -> bool:
        """更新现有模板"""
        if template_name not in self.templates:
            return False
        template = self.templates[template_name]
        template.update(updates)
        template['updated_at'] = datetime.now().isoformat()
        return self.save_templates()
    
    def delete_template(self, template_name: str) -> bool:
        """删除模板"""
        if template_name not in self.templates:
            return False
        del self.templates[template_name]
        return self.save_templates()
    
    def validate_template_variables(self, template: Dict, variables: Dict) -> bool:
        """验证模板变量"""
        required_vars = set(template.get('variables', []))
        provided_vars = set(variables.keys())
        return required_vars == provided_vars
    
    def get_templates_by_category(self, category: str) -> List[Dict]:
        """获取指定分类的所有模板"""
        return [template for template in self.templates.values()
                if template.get('category') == category]
    
    def get_all_categories(self) -> List[str]:
        """获取所有模板分类"""
        return list(set(template.get('category') for template in self.templates.values()
                      if template.get('category')))
    
    def format_prompt(self, template_id: str, **kwargs) -> Optional[str]:
        """使用变量格式化模板"""
        template = self.get_template(template_id)
        if not template:
            return None
        try:
            return template['template'].format(**kwargs)
        except Exception as e:
            print(f'格式化模板失败: {e}')
            return None